#include "basketballwidget.h"
#include <QVBoxLayout>
#include <QSqlQuery>
#include "calculation.h"
#include <QDebug>

const char* const CompareType[] = {
    "BS",
    "SF",
    "UNDEFIN"
};

typedef enum{
    BS=0,
    SF,
    MAX_COMPARETYPE
}__CompareTypeEnum;


BasketballWidget::BasketballWidget(QWidget *parent) :
    QWidget(parent)
{
    setAutoFillBackground(true);

    m_TableWidget = new QTableWidget();

    QVBoxLayout * mainLayout = new QVBoxLayout();

    mainLayout->addWidget(m_TableWidget);


    setLayout(mainLayout);

    TableWidgetInit();

    DisplayAllData();

    connect(m_TableWidget,SIGNAL(cellChanged(int,int)),this,SLOT(OnTableWidgetCellChanged(int,int)));
}


void BasketballWidget::TableWidgetInit()
{
    m_TableWidget->setColumnCount(9);
    m_ColOrder = new Qt::SortOrder [9] ;
//    m_TableWidget->setRowCount(50);
    m_TableWidget->setSortingEnabled(true);
//    m_TableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);//disable edit
//    m_TableWidget->resize(350, 250);
    m_TableWidget->setColumnWidth(0,50);
    m_TableWidget->setColumnWidth(1,50);
    m_TableWidget->setColumnWidth(2,50);
    m_TableWidget->setColumnWidth(3,50);
    m_TableWidget->setColumnWidth(4,100);
    m_TableWidget->setColumnWidth(5,560);
    m_TableWidget->setColumnWidth(6,300);
    m_TableWidget->setStyleSheet("QTableWidget{background-color: rgba(0,0,0,0);border-width:1;border-style:outset}");


    m_TableWidget->clear();

   m_TableWidget->setRowCount(0);

    QStringList headers;
    headers<<tr("CompareType")<< tr("Comparefraction") <<tr("HomeTeam")<<tr("VisitingTeam")<<tr("Result")
          <<tr("calculate") << tr("calculateResult") << tr("Multiple") << tr("recoed")  << tr("Date") ;
    m_TableWidget->setHorizontalHeaderLabels(headers);



}

void BasketballWidget::OnTableWidgetCellChanged(int row, int column)
{
    qDebug() << "row " << row << "column " << column;
}


void BasketballWidget::DisplayAllData()
{
    QSqlQuery q;
 //   q.exec("SELECT date,CompareType,HomeTeam,VisitingTeam,Result,Comparefraction,Recoed,Multiple FROM t_basketboll");
    q.exec("SELECT * FROM t_basketboll");
    QStringList rowData;
    int rowNum=0;
    while (q.next())
    {
       rowData.clear();
       QString Calculate_str = DoCalculate( q.value("Multiple").toString(),
                                            q.value("Recoed").toString(),
                                            q.value("CompareType").toString(),
                                            q.value("Comparefraction").toString());

       rowData<<q.value("CompareType").toString() << q.value("Comparefraction").toString()
                << q.value("HomeTeam").toString() << q.value("VisitingTeam").toString() << q.value("Result").toString()
               << Calculate_str << DocalculateResult(Calculate_str,
                                                     q.value("Result").toString(),
                                                     q.value("CompareType").toString(),
                                                     q.value("Comparefraction").toString())
               << q.value("Multiple").toString() << q.value("Recoed").toString() << q.value("date").toString();


       TableWidgetInsertRows(rowData,rowNum++);

    }
}

//QString BasketballWidget::Do
// "\n" --> "=" -> ";" -> ":"
QString BasketballWidget::DoRecoedCalculate(const QString & Recoed)
{
    QStringList LineList = Recoed.split("\n");

    QStringList HV_H_list;
    QStringList HV_V_list;
    QStringList HV_sum_list;
    QStringList HO_H_list;
    QStringList HO_O_list;

    QStringList VO_V_list;
    QStringList VO_O_list;
    qDebug() << "LineList" << LineList;
    QString LineStr;
    foreach(LineStr,LineList)
    {
        QStringList TypeValueList = LineStr.split("=");
        qDebug() << "ValueList" << TypeValueList;
        if(TypeValueList.count() != 2)
        {
            continue;
        }
        QString TypeValueStr_V = TypeValueList.at(1);
        QString TypeValueStr_T = TypeValueList.at(0);
        qDebug() << "TypeValueStr_V : " << TypeValueStr_V << "TypeValueStr_T "  << TypeValueStr_T;

       // foreach(TypeValueStr,TypeValueList)
        {
             QStringList HVO_ValueList = TypeValueStr_V.split(";");
             qDebug() << "HVO_ValueList " << HVO_ValueList;
             QString HVO_ValueStr;
             foreach(HVO_ValueStr,HVO_ValueList)
             {
                QStringList HVO_ValueList = HVO_ValueStr.split(":");
                qDebug() << "HVO_ValueStr " << HVO_ValueList;
                if(HVO_ValueList.count() != 2)
                    continue;
                if(TypeValueStr_T == "HV")
                {
                    HV_H_list << HVO_ValueList.at(0);
                    HV_V_list << HVO_ValueList.at(1);
                    HV_sum_list << QString::number(HVO_ValueList.at(0).toInt() + HVO_ValueList.at(1).toInt());
                }
                else if(TypeValueStr_T == "HO")
                {
                    HO_H_list << HVO_ValueList.at(0);
                    HO_O_list << HVO_ValueList.at(1);
                }
                else if(TypeValueStr_T == "VO")
                {
                    VO_V_list << HVO_ValueList.at(0);
                    VO_O_list << HVO_ValueList.at(1);
                }

             }
        }
    }

//////////////////////////////////

    int HV_sum = Calculation::AveViule(HV_sum_list);

////////////////////////////////////////////////////////////
    int HVO_HVSA  = Calculation::AveViule(HO_H_list) +Calculation::AveViule(VO_V_list) ;
/////////////////////////////////////////////////////////

    int HO_MIN_H = Calculation::MinViule(HO_H_list);
    int HO_MIN_O = Calculation::MinViule(HO_O_list);
    int HO_MAX_H = Calculation::MaxViule(HO_H_list);
    int HO_MAX_O = Calculation::MaxViule(HO_O_list);

    int VO_MIN_V = Calculation::MinViule(VO_V_list);
    int VO_MIN_O = Calculation::MinViule(VO_O_list);
    int VO_MAX_V = Calculation::MaxViule(VO_V_list);
    int VO_MAX_O = Calculation::MaxViule(VO_O_list);

    int HVO_MIN_HVS = VO_MIN_V + HO_MIN_H;
    int HVO_MAX_HVS = VO_MAX_V + HO_MAX_H;








    QString RetStr;

    RetStr += QString("HVO_HVSA=%1;HV_HVSA=%2;").arg(HVO_HVSA).arg(HV_sum);
     RetStr +=  QString("HVO_MIN_HVS~HVO_MAX_HVS=%1~%2;").arg(HVO_MIN_HVS).arg(HVO_MAX_HVS);


    QDebug(&RetStr)  << "||||||||";
    QDebug(&RetStr)  << "\n_A = AVERAGE _S = SUM _R=range";
    QDebug(&RetStr)  << "\nHV_H_list" << HV_H_list;
    QDebug(&RetStr)  << "\nHV_V_list" << HV_V_list;
    QDebug(&RetStr)  << "\nHV_sum_list" << HV_sum_list;
    QDebug(&RetStr)  << "\nHO_H_list" << HO_H_list;
    QDebug(&RetStr)  << "\nVO_V_list" << VO_V_list;
    QDebug(&RetStr)  << "\nHO_O_list" << HO_O_list;
    QDebug(&RetStr)  << "\nVO_O_list" << VO_O_list;
    QDebug(&RetStr)  << "\n HO_MIN_H" << HO_MIN_H;
    QDebug(&RetStr)  << "\n HO_MIN_O" << HO_MIN_O;
    QDebug(&RetStr)  << "\n HO_MAX_H" << HO_MAX_H;
    QDebug(&RetStr)  << "\n HO_MAX_O" << HO_MAX_O;
    QDebug(&RetStr)  << "\n VO_MIN_V" << VO_MIN_V;
    QDebug(&RetStr)  << "\n VO_MIN_O" << VO_MIN_O;
    QDebug(&RetStr)  << "\n VO_MAX_V" << VO_MAX_V;
    QDebug(&RetStr)  << "\n VO_MAX_O" << VO_MAX_O;


    qDebug() << RetStr;

    return RetStr;
}

QString  BasketballWidget::DoCalculate(const QString & Multiple, const QString & Recoed,
                                       const QString & CompareType,const QString &Comparefraction)
{

    Q_UNUSED(Multiple);
    Q_UNUSED(CompareType);
    Q_UNUSED(Comparefraction);


    return DoRecoedCalculate(Recoed);

}

QString BasketballWidget::DoRecoedCalculateResult(const QString & Calculate,const QString & Result,const QString &Comparefraction)
{
    int sum_result = 0;
    QString RetStr = "";
    QStringList list = Result.split("=");
    qDebug() << "list-------------------" << list;
    if(list.count() != 2)
    {
        return "";
    }
    list = list.at(1).split(":");
    if(list.count() != 2)
    {
        return "";
    }
    sum_result = list.at(0).toInt() + list.at(1).toInt();
    RetStr += "result:"+QString::number(sum_result)+"\n\n";
    QString B_S;
    if((qreal)sum_result > Comparefraction.toFloat())
    {
        B_S = "B";
    }
    else
    {
        B_S = "S";
    }

    list = Calculate.split("||||||||");
    qDebug() << "list-------------------" << list;
    if(list.count() != 2)
    {
        return "";
    }

    QStringList CalculateList = list.at(0).split(";");
    qDebug() << "CalculateList-------------------" << CalculateList;
    QString value;
    foreach (value, CalculateList) {
        QStringList ValueList = value.split("=");
        if(ValueList.count() != 2)
            continue;
        if(ValueList.at(0).indexOf("~") < 0)
        {
            if(B_S == "B")
            {
                if(ValueList.at(1).toFloat() > Comparefraction.toFloat())
                {
                    RetStr += value+"\n";
                }
            }
            else
            {
                if(ValueList.at(1).toFloat() < Comparefraction.toFloat())
                {
                    RetStr += value + "\n";
                }
            }
        }
        else
        {

            QStringList tmpList = ValueList.at(1).split("~");
            qDebug() << "tmpList --------------------------------------------= " << tmpList;
            if(tmpList.at(0).toInt() <=  sum_result &&  sum_result <= tmpList.at(1).toInt() )
            {
                RetStr += value + "\n";
            }
        }
    }


    //qDebug() << "list :" << list;

    return RetStr;

}


QString  BasketballWidget::DocalculateResult(const QString & Calculate, const QString & Result,const QString & CompareType,const QString &Comparefraction)
{

    Q_UNUSED(CompareType);

    return DoRecoedCalculateResult(Calculate,Result,Comparefraction);//Calculate + Result + CompareType;
}


void BasketballWidget::TableWidgetInsertRows(const QStringList &list,int row)
{
    int col=0;
    QString str;
    m_TableWidget->insertRow(row);
    m_TableWidget->setRowHeight(row,300);

    foreach(str,list)
    {
        QTableWidgetItem * item = new QTableWidgetItem(str);
        item->setData(Qt::DisplayRole,str); //sort by  id -> str.toInt
        m_TableWidget->setItem(row,col++,item);
    }
}

void BasketballWidget::TableWidgetSortByColumn(int col)
{
    if(m_ColOrder[col] != Qt::AscendingOrder)
    {
        m_TableWidget->sortByColumn(col, Qt::AscendingOrder);
        m_ColOrder[col] = Qt::AscendingOrder;
    }
    else
    {
        m_TableWidget->sortByColumn(col, Qt::DescendingOrder);
        m_ColOrder[col] = Qt::DescendingOrder;
    }
}

void BasketballWidget::keyReleaseEvent(QKeyEvent * event)
{
    if(event->key() == Qt::Key_F5)
     {
        qDebug() << "Qt::Key_F5";
         TableWidgetInit();
         DisplayAllData();
     }
}
